using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
using PowerManage.API.RateLimiter;

namespace PowerManage.API.Extensions;

/// <summary>
/// 速率限制扩展
///提供速率限制器算法:官方提供的算法有4个：
///1.固定窗口限制器
///2.滑动窗口限制器
///3.令牌桶限制程序
///4.并发限制器
/// </summary>
public static class RateLimiterExtension
{
    /// <summary>
    /// 添加速率限制
    /// </summary>
    /// <param name="builder"></param>
    public static void AddPowerManageRateLimiter(this WebApplicationBuilder builder)
    {
        //添加速率限制
        builder.Services.AddRateLimiter(options =>
        {
            //添加固定窗口策略
            options.AddFixedWindowLimiter(RateLimiterPolicyName.LoginPolicy, limiterOptions =>
            {
                limiterOptions.Window = TimeSpan.FromSeconds(10); //窗口大小 10秒
                limiterOptions.PermitLimit = 1; //窗口内允许的最大请求数
                limiterOptions.QueueLimit = 5; //队列长度
                limiterOptions.QueueProcessingOrder = QueueProcessingOrder.OldestFirst; //队列处理顺序
                limiterOptions.QueueLimit = 1; //队列长度
            });
        });
    }
}